package com.qf.mybatisplus.utils;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.qf.mybatisplus.vo.ZsVo;

import java.io.*;
import java.util.List;
import java.util.*;

/**
 * @program: hzmoko
 * @description: pdf填充数据
 * @author: ZKN
 * @create: 2020-03-31 13:12
 **/
public class PdfTemplateUtil {
    /**
     * @author zhang
     * @date 2018/08/01
     */

    public static void fillTemplate(String templatePath, String newPDFPath, Map<String, String> mMapDatas) {
//        // 模板路径
//        String templatePath = "D:\\java\\nginx-1.15.0\\html\\MOKO-IMG\\衡阳市不动产继承问询记录-复制(1).pdf";
//        // 生成的新文件路径
//        String newPDFPath = "D:\\java\\nginx-1.15.0\\html\\MOKO-IMG\\测试.pdf";
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            File file = new File(newPDFPath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            out = new FileOutputStream(newPDFPath);
            reader = new PdfReader(templatePath);
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();

            int i = 0;
            Iterator<String> it = form.getFields().keySet().iterator();
            while (it.hasNext()) {
                String name = it.next();
                form.setField(name, mMapDatas.get(name));
            }
            //true代表生成的PDF文件不可编辑
            stamper.setFormFlattening(true);
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    public static void fillTemplate(String templatePath, String newPDFPath, Map<String, String> mMapDatas, Map<String, String> pictureData) {
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            out = new FileOutputStream(newPDFPath);
            reader = new PdfReader(templatePath);
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            Iterator<String> it = mMapDatas.keySet().iterator();
            while (it.hasNext()) {
                String name = it.next();
                form.setField(name, mMapDatas.get(name));
            }
            if (pictureData != null) {
                Iterator<String> picIterator = pictureData.keySet().iterator();
                while (picIterator.hasNext()) {
                    String fieldName = picIterator.next();
                    // 通过域名获取所在页和坐标，左下角为起点
                    int pageNo = form.getFieldPositions(fieldName).get(0).page;
                    Rectangle signRect = form.getFieldPositions(fieldName).get(0).position;
                    float x = signRect.getLeft();
                    float y = signRect.getBottom();

                    // 读图片
                    Image image = Image.getInstance(pictureData.get(fieldName));
                    // 获取操作的页面
                    PdfContentByte under = stamper.getOverContent(pageNo);
                    // 根据域的大小缩放图片
                    image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                    // 添加图片
                    image.setAbsolutePosition(x, y);
                    under.addImage(image);
                }

            }
            //true代表生成的PDF文件不可编辑
            stamper.setFormFlattening(true);
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }


    /**
     * @return void
     * @Description 旋转PDF 180°
     * @Param []
     * @Author ZDD
     * @Date 14:26 2021/11/2
     **/
    public static String rotatePdf(String uuid) {
        Document document = null;
        // 切勿将源文件和输出文件使用一个路径，否则会出现异常：
        // Exception in thread "main" java.io.FileNotFoundException:
        PdfCopy p = null; // 生成的目标PDF文件
        PdfReader reader = null;

        String diskPath = EnvUtils.getProperty("hzmoko.img.diskPath");
        String pdfPath = diskPath + "creatProofPDF/" + uuid + ".pdf";
        String rotatePdfPath = diskPath + "creatProofPDF/" + uuid + "rotatePdf.pdf";
        try {
            reader = new PdfReader(pdfPath); // 读取源文件
            document = new Document(); // 建立文档
            p = new PdfSmartCopy(document, new FileOutputStream(rotatePdfPath));
            document.open();

            int n = reader.getNumberOfPages(); // 获取源文件的页数
            PdfDictionary pd;
            for (int j = 1; j <= n; j++) {
                pd = reader.getPageN(j);
                // 顺时针旋转180°,只有里面写270才旋转180°，服了
                pd.put(PdfName.ROTATE, new PdfNumber(270));
            }
            for (int page = 0; page < n; ) {
                p.addPage(p.getImportedPage(reader, ++page));
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        reader.close();
        document.close();
        return rotatePdfPath;

    }

    /**
     * @return java.lang.String
     * @Description 用于国产 统信UOS系统证明生成PDF
     * @Param [staticDataList, uuid]
     * @Author 12136
     * @Date 14:35 2021/11/3
     **/

    public static void main(String[] args) {
        Map<String, String> mMapDatas = new HashMap<>();
        Map<String, String> pictureData = new HashMap<>();
        mMapDatas.put("gyqk", "单独所有");
        mMapDatas.put("name", "刘美林");
        mMapDatas.put("bdcqzh", "浙(2019)杭州市不动产权第10000010号");
        mMapDatas.put("zl", "江干区亨奇克拉天禧");
        mMapDatas.put("bdcdyh", "2154545154645");
        mMapDatas.put("qllx", "国有建设用地使用权/房屋(构筑物)所有权");
        mMapDatas.put("qlxz", "出让/存量房");
        mMapDatas.put("yt", "商服用地/非住宅");
        mMapDatas.put("mj", "土地使用权面积59㎡/房屋建筑面积90㎡");
        mMapDatas.put("syqx", "国有建设用地使用权2099年11月16日止");
        mMapDatas.put("qt", "土地使用权面积：59㎡，其中独用土地面积0㎡，分摊土地面积9.0㎡");

        List<ZsVo> zsVoList = new ArrayList<>();
        zsVoList.add(0, new ZsVo("bdcqzh", "浙 ( 2019 ) 杭州市 不动产权第 10000010 号", "不动产权证号"));
        zsVoList.add(1, new ZsVo("name", "刘美林", "姓      名"));
        zsVoList.add(2, new ZsVo("gyqk", "单独所有", "共有情况"));
        zsVoList.add(3, new ZsVo("zl", "江干区亨奇克拉天禧", "坐      落"));
        zsVoList.add(4, new ZsVo("bdcdyh", "2154545154645", "单 元 号"));
        zsVoList.add(5, new ZsVo("qllx", "国有建设用地使用权/房屋(构筑物)所有权", "类      型"));
        zsVoList.add(6, new ZsVo("qlxz", "出让/存量房", "性      质"));
        zsVoList.add(7, new ZsVo("yt", "商服用地/非住宅", "用      途"));
        zsVoList.add(8, new ZsVo("mj", "土地使用权面积59㎡/房屋建筑面积90㎡", "面      积"));
        zsVoList.add(9, new ZsVo("syqx", "国有建设用地使用权2099年11月16日止", "使用期限"));
        zsVoList.add(10, new ZsVo("qt", "土地使用权面积：59㎡，其中独用土地面积0㎡，分摊土地面积9.0㎡", "其\n他\n情\n况"));

        String[] bdcqzh = {"浙", "2020", "杭州市", "杭州摩科第 01010001 号"};
        // 新建document对象
        Document document = new Document();
        Rectangle pageSize = new Rectangle(PageSize.A4); // X:595,y:842
        // 将PDF由纵向设置为横向
        pageSize = pageSize.rotate();
        pageSize.setBackgroundColor(new BaseColor(181, 167, 154, 100));
        document.setPageSize(pageSize);
        // left right top bottom
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\moko\\nginx-1.20.1\\html\\MOKO-IMG\\creatProofPDF\\证书预览.pdf"));
            document.open();

            // start
//            BaseFont baseFont1 = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
//            Font songti09 = new Font(baseFont1, 9f);
            //添加中文字体
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            //设置字体样式
            Font textFont = new Font(bfChinese, 12, Font.NORMAL);//正常
            Font bigFont = new Font(bfChinese, 16, Font.NORMAL);//正常
            Font textFontSmall = new Font(bfChinese, 8, Font.NORMAL);//小号
            Font boldFont = new Font(bfChinese, 11, Font.BOLD); //加粗
            Font boldBigFont = new Font(bfChinese, 15, Font.BOLD); //加粗

            PdfPTable table = new PdfPTable(2);
            PdfPTable table1 = new PdfPTable(1);
            PdfPTable table2 = new PdfPTable(4);

            Chunk chunkCell1 = new Chunk(bdcqzh[0], bigFont);
            chunkCell1.setUnderline(0.1f, -2f);
            PdfPCell cell01 = new PdfPCell(new Paragraph(chunkCell1));
            cell01.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);//水平居中
            cell01.setBorderWidth(0);
            table2.addCell(cell01);

            Chunk chunkCell2 = new Chunk("( " + bdcqzh[1] + " )", bigFont);
            PdfPCell cell02 = new PdfPCell(new Paragraph(chunkCell2));
            cell02.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);//水平居中
            cell02.setBorderWidth(0);
            table2.addCell(cell02);

            Chunk chunkCell3 = new Chunk(bdcqzh[2], bigFont);
            chunkCell3.setUnderline(0.1f, -2f);
            PdfPCell cell03 = new PdfPCell(new Paragraph(chunkCell3));
            cell03.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);//水平居中
            cell03.setBorderWidth(0);
            table2.addCell(cell03);

            Chunk chunkCell4 = new Chunk(bdcqzh[3], bigFont);
            PdfPCell cell04 = new PdfPCell(new Paragraph(chunkCell4));
            cell04.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);//水平居中
            cell04.setBorderWidth(0);
            table2.addCell(cell04);


            // 设置每列的宽度
            table.setTotalWidth(new float[]{50, 200});
            table2.setTotalWidth(new float[]{30, 70, 70, 200});

            for (int i = 0; i < zsVoList.size() - 1; i++) {

                PdfPCell cell1;
                PdfPCell cell2;
//                if (i == 0) {
//                    Chunk chunk = new Chunk(zsVoList.get(0).getValue(),bigFont);
//                    chunk.setUnderline(0.1f, -2f);
//                    cell1 = new PdfPCell(new Paragraph(chunk));
//                    cell2 = new PdfPCell(new Paragraph("姓  名",textFont));
//                    cell1.setMinimumHeight(50);
//                    cell1.setColspan(2);
//                    cell1.setBorderWidth(0);
//                    cell1.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);//水平居中
//                    cell1.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);//底部显示
//                    cell2.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);//水平居中
//                    cell2.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);//垂直居中
//                }else
                if (i == zsVoList.size() - 2) {
                    cell1 = new PdfPCell(new Paragraph(zsVoList.get(zsVoList.size() - 1).getValue2(), textFont));
                    cell2 = new PdfPCell(new Paragraph(zsVoList.get(zsVoList.size() - 1).getValue(), textFont));
                    cell1.setMinimumHeight(170);

                    cell1.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);//水平居中
                    cell1.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);//垂直居中

                    cell2.setMinimumHeight(170);
                    cell2.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);//水平居中
                    cell2.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);//垂直居中
                } else {
                    cell1 = new PdfPCell(new Paragraph(zsVoList.get(i + 1).getValue2(), textFont));
                    cell2 = new PdfPCell(new Paragraph(zsVoList.get(i + 1).getValue(), textFont));
                    cell1.setMinimumHeight(40);
                    cell1.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);//水平居中
                    cell1.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);//垂直居中

                    cell2.setMinimumHeight(40);
                    cell2.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);//水平居中
                    cell2.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);//垂直居中
                }
                table.addCell(cell1);
                table.addCell(cell2);

            }

            PdfPCell pdfPCell2 = new PdfPCell(new Paragraph("附   记", bigFont));
            pdfPCell2.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);//水平居中
            pdfPCell2.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);//垂直居中
            pdfPCell2.setMinimumHeight(50);
            pdfPCell2.setBorderWidth(0);

            PdfPCell pdfPCell1 = new PdfPCell(new Paragraph("测试数据", textFont));
            pdfPCell1.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);//水平居中
            pdfPCell1.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);//垂直居中
            pdfPCell1.setMinimumHeight(530);


            table1.addCell(pdfPCell2);
            table1.addCell(pdfPCell1);

            PdfContentByte canvas = writer.getDirectContent();
            table.setTotalWidth(370f);
            table1.setTotalWidth(370f);

            /**
             * rowStart         0   起始行
             * rowEnd           -1  表示全部行
             * xPos             表格横坐标- 从左向右开始计算
             * yPos             表格纵坐标- 从下向上开始计算
             * canvas           画布
             */
            table.writeSelectedRows(0, -1, 30, 550, canvas);
            table1.writeSelectedRows(0, -1, 450, 600, canvas);
            table2.writeSelectedRows(0, -1, 30, 580, canvas);

            document.close();
            writer.close();

        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
    }


}